%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     网络 http 服务
%%% @end
%%%-------------------------------------------------------------------
-module(net_http_srv).

-behaviour(gen_server).

-export([start_link/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-include("common.hrl").
-include("env.hrl").


%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link() ->
    ?ECHO("正在启动[~w]", [?MODULE]),
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).


init([]) ->
    erlang:process_flag(trap_exit, true),
    start_cowboy(),
    ?ECHO("完成启动[~w] 端口:~w", [?MODULE, env_mgr:get(?ENV_NET_HTTP_PORT)]),
    {ok, undefined}.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    cowboy:stop_listener(?MODULE),
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


%%%===================================================================
%%% Internal functions
%%%===================================================================

start_cowboy() ->
    HttpPort = env_mgr:get(?ENV_NET_HTTP_PORT),
    WSUri = env_mgr:get(?ENV_NET_WEBSOCKET_URI),
    WebUri = env_mgr:get(?ENV_NET_WEB_URI),

    Dispatch = cowboy_router:compile([
        {'_', [
            {WSUri, net_http_websocket_handler, []}
            ,{WebUri, net_http_web_handler, []}
        ]}
    ]),

    {ok, _} = cowboy:start_clear(?MODULE, [{port, HttpPort}], #{env => #{dispatch => Dispatch}}).
